package io.gitee.hefren.hhregistry.service.impl;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import io.gitee.hefren.hhregistry.beans.InstanceMeta;
import io.gitee.hefren.hhregistry.service.RegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * RegisterService 默认实现
 * @Date 2024/5/13
 * @Author lifei
 */
public class HhRegisterService implements RegisterService {

    private static final Logger log = LoggerFactory.getLogger(HhRegisterService.class);

    private static final MultiValueMap<String, InstanceMeta> INSTANCES = new LinkedMultiValueMap<>();

    private static final Map<String, Long> VERSIONS = Maps.newConcurrentMap();
    private static final AtomicLong VERSION = new AtomicLong(0);
    public static final Map<String, Long> TIMESTEMPS = Maps.newConcurrentMap();

    @Override
    public InstanceMeta register(String server, InstanceMeta instance) {
        List<InstanceMeta> instanceMetas = INSTANCES.get(server);
        if (Objects.nonNull(instanceMetas) && !instanceMetas.isEmpty()) {
            if (instanceMetas.contains(instance)) {
                log.debug("==> already exists server: {}, instance: {}", server, instance);
                instance.setStatus(true);
                return instance;
            }
        }
        log.debug("==> register server: {}, instance: {}", server, instance);
        instance.setStatus(true);
        INSTANCES.add(server, instance);
        renew(instance, server);
        updateVersion(server);
        return instance;
    }

    @Override
    public InstanceMeta unregister(String server, InstanceMeta instance) {
        List<InstanceMeta> instanceMetas = INSTANCES.get(server);
        if (Objects.isNull(instanceMetas) || instanceMetas.isEmpty()) {
            log.debug("==> not exists server: {}, instance: {}", server, instance);
            instance.setStatus(false);
            return instance;
        }
        log.debug("==> unregister server: {}, instance: {}", server, instance);
        instanceMetas.removeIf(k->k.equals(instance));
        instance.setStatus(false);
        renew(instance, server);
        updateVersion(server);
        return instance;
    }

    /**
     * 更新server的版本
     * @param server
     */
    private void updateVersion(String server) {
        VERSIONS.put(server, VERSION.getAndIncrement());
    }

    @Override
    public List<InstanceMeta> findAllInstances(String server) {
        return INSTANCES.get(server);
    }

    @Override
    public Long version(String server) {
        return VERSIONS.get(server);
    }

    @Override
    public Map<String, Long> versions(String... servers) {
        return Arrays.stream(servers).collect(Collectors.toMap(k->k, VERSIONS::get, (v1, v2)->v2));
    }

    @Override
    public Long renew(InstanceMeta instance, String... servers) {
        long now = System.currentTimeMillis();
        for (String server : servers) {
            String serverAndInstance = Strings.lenientFormat("%s@%s", server, instance.toUrl());
            TIMESTEMPS.put(serverAndInstance, now);
        }
        return now;
    }
}
